<template>
  <div class="app-container">
    <div class="container_box">
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="14" :xl="12">
          <el-form ref="form" :model="form" :rules="rules" label-width="110px">
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="報價編碼" prop="quoteCode">
                  <el-input
                    disabled
                    v-model="form.quoteCode"
                    placeholder="請輸入標題"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="來源" prop="sourceType">
                  <el-select
                    style="width: 100%"
                    v-model="sourceType"
                    placeholder="請選擇來源"
                    @change="sourceTypeChange"
                  >
                    <el-option
                      v-for="dict in dict.type.quote_source"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="標題" prop="quoteTitle">
                  <el-input
                    v-model="form.quoteTitle"
                    placeholder="請輸入標題"
                  />
                </el-form-item>
              </el-col>
            
        
            </el-row>
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="報價人" prop="quoterName">
                  <el-input
                    disabled
                    v-model="form.quoterName"
                    placeholder="請輸入報價人"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row> </el-row>
            <!-- 預約跳轉 -->
            <el-row v-if="sourceType == '10'">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="預約編碼" prop="reservationCode">
                  <el-input
                    disabled
                    v-model="form.reservationCode"
                    placeholder="請選擇預約編碼"
                  >
                    <el-button
                      slot="append"
                      @click="open_dialog_reservation"
                      icon="el-icon-search"
                    ></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="客戶編碼" prop="customerCode">
                  <el-input
                    disabled
                    v-model="form.customerCode"
                    placeholder="請選擇客戶編碼"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="客戶名稱" prop="customerName">
                  <el-input
                    disabled
                    v-model="form.customerName"
                    placeholder="請選擇客戶名稱"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="sourceType == '20'">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="客戶編碼" prop="customerCode">
                  <el-input
                    disabled
                    v-model="form.customerCode"
                    placeholder="請選擇客戶編碼"
                  >
                    <el-button
                      slot="append"
                      @click="open_dialog_customer"
                      icon="el-icon-search"
                    ></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="客戶名稱" prop="customerName">
                  <el-input
                    disabled
                    v-model="form.customerName"
                    placeholder="請選擇客戶名稱"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="入賬銀行賬號" prop="inBankNo">
                  <el-input
                    disabled
                    v-model="form.inBankNo"
                    placeholder="請選擇賬銀行賬號"
                  >
                    <el-button
                      slot="append"
                      @click="open_dialog_bank"
                      icon="el-icon-search"
                    ></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="入賬銀行名稱" prop="inBankName">
                  <el-input
                    disabled
                    v-model="form.inBankName"
                    placeholder="請輸入入賬銀行名稱"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="有效天數" prop="validDays">
                  <el-input
                    v-model="form.validDays"
                    placeholder="請輸入有效天數"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="稅率" prop="taxRate">
                  <el-input
                    maxlength="4"
                    placeholder="請輸入稅率（0-1）"
                    @change="taxRate_change"
                    oninput="value=value.replace(/^0[0-9]|^[2-9]|^1[0-9]|^1\.|[^\d.]/g,'')"
                    v-model="form.taxRate"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="備註" prop="remark">
                  <el-input v-model="form.remark" placeholder="請輸入備註" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-divider content-position="center">報價單明細</el-divider>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="add"
                >添加</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="del"
                >删除</el-button
              >

              <el-table
                style="width: 100%"
                :data="bizQuoteItemList"
                :row-class-name="rowItemIndex"
                :row-key="
                  (row) => {
                    return row.index;
                  }
                "
                @selection-change="SelectionChange"
                ref="bizCustomerReservationItem"
              >
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column
                  label="序號"
                  align="center"
                  prop="index"
                  width="50"
                />
                <el-table-column label="報價事項" align="center" prop="itemKey">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.itemKey"
                      placeholder="請選擇報價事項"
                      clearable
                    >
                      <el-option
                        v-for="dict in dict.type.business_scope"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="報價金額"
                  align="center"
                  prop="itemAmount"
                >
                  <template slot-scope="scope">
                    <el-input
                      min="0"
                      @change="amountSum(scope.row)"
                      v-model="scope.row.itemAmount"
                      placeholder="請輸入報價金額"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="備註" prop="remark">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.remark"
                      placeholder="請輸入備註"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="稅金" align="center" prop="taxAmount">
                  <template slot-scope="scope">
                    <span v-if="scope.row.itemAmount">{{
                      scope.row.taxAmount
                    }}</span>
                    <span v-else>0</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="報價含稅金額"
                  align="center"
                  prop="itemTaxAmount"
                >
                  <template slot-scope="scope">
                    <span v-if="scope.row.itemAmount">{{
                      scope.row.itemTaxAmount
                    }}</span>
                    <span v-else>0</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>

          <div style="text-align: center; margin-top: 16px">
            <el-button type="primary" @click="submitForm('20')"
              >提 交</el-button
            >
            <el-button type="primary" @click="submitForm('10')"
              >保 存</el-button
            >
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 選擇客戶  -->
      <el-dialog
        :visible.sync="dialog_if_customer"
        destroy-on-close
        :close-on-click-modal="false"
        width="1000px"
        append-to-body
      >
        <single-table
          :selected="selected_customer_id"
          @customer_detail="customer_detail"
          @customer_cancel="customer_cancel"
        >
        </single-table>
      </el-dialog>

      <!-- 選擇入賬銀行 -->
      <el-dialog
        :visible.sync="dialog_if_bank"
        destroy-on-close
        :close-on-click-modal="false"
        width="1000px"
        append-to-body
      >
        <bank-table
          :selected="selected_bank_id"
          @out_detail="bank_detail"
          @out_cancel="bank_cancel"
          :type="10"
        >
        </bank-table>
      </el-dialog>

      <!-- 選擇預約 -->
      <el-dialog
        :visible.sync="dialog_if_reservation"
        destroy-on-close
        :close-on-click-modal="false"
        width="1000px"
        append-to-body
      >
        <reservation-table
          :selected="selected_reservation_id"
          @out_detail="reservation_detail"
          @out_cancel="reservation_cancel"
        >
        </reservation-table>
      </el-dialog>
    </div>
  </div>
</template>
  
  <script>
import {
  getQuote,
  updateQuote,
} from "@/api/biz/quote";

import singleTable from "@/components/biz/singleTable";
import bankTable from "@/components/biz/bankTable";
import reservationTable from "@/components/biz/reservationTable";
export default {
  components: { singleTable, bankTable, reservationTable },
  name: "QuoteAdd",
  dicts: [
    "customer_type",
    "customer_tag",
    "customer_source",
    "industry_type",
    "cart_type",
    "sys_user_sex",
    "customer_level",
    "bank_type",
    "sys_yes_no",
    "sys_normal_disable",
    "quote_source",
    "quote_status",
    "business_scope",
  ],
  data() {
    return {
      // 表单參數
      form: {
        quoterName: this.$store.state.user.nickName,
        validDays: 30,
        taxRate: 0,
      },

      // 表单校验
      rules: {},
      title: "",
      // 是否顯示弹出层
      loading: false,
      // 報價單明細表格數据
      bizQuoteItemList: [],
      checkedList: [],
      //------------------------

      // 選擇客戶詳細信息
      dialog_if_customer: false,
      selected_customer_id: "",

      // 選擇銀行詳細信息
      dialog_if_bank: false,
      selected_bank_id: "",
      // 選擇預約詳細信息
      dialog_if_reservation: false,
      selected_reservation_id: "",
      // 來源
      sourceType: this.$route.query.quoteSource,
    };
  },
  created() {
    if (this.$route.query.id) {
      console.log(this.$route.query);
      this.get_detail(this.$route.query.id);
    }
  },
  activated() {
    if (this.$route.query.id) {
      this.get_detail(this.$route.query.id);
    }
  },
  methods: {
    // 獲取詳情
    get_detail(id) {
      getQuote(id).then((response) => {
        console.log(response.data);
        this.form.id = response.data.id;
        this.form.quoteSource = response.data.quoteSource;
        this.form.quoteCode = response.data.quoteCode;
        this.form.quoteTitle = response.data.quoteTitle;
        
              

        if (response.data.quoteSource == 10) {
          // 預約
          this.selected_reservation_id = response.data.reservationId;
          this.form.reservationId = response.data.reservationId;
          this.form.reservationCode = response.data.reservationCode;
        }
        this.selected_customer_id = response.data.customerId;
        this.form.customerId = response.data.customerId;
        this.form.customerCode = response.data.customerCode;
        this.form.customerName = response.data.customerName;
        
        this.form.selected_bank_id = response.data.inBankId;
        this.form.inBankId = response.data.inBankId;
        this.form.inBankNo = response.data.inBankNo;
        this.form.inBankName = response.data.inBankName;
        this.form.inBankAccount = response.data.inBankAccount;


        this.form.validDays = response.data.validDays;
        this.form.remark = response.data.remark;
        this.form.taxRate = response.data.taxRate;
        this.form.quoteAmount = response.data.quoteAmount;
        this.form.quoteTaxAmount = response.data.quoteTaxAmount;
        this.form.taxAmount = response.data.taxAmount;


        this.bizQuoteItemList = [];
        response.data.bizQuoteItemList.map((item) => {
          let obj = {
            itemKey: item.itemKey,
            itemAmount: item.itemAmount,
            taxAmount: item.taxAmount,
            itemTaxAmount: item.itemTaxAmount,
            taxRate: item.taxRate,
            quantity: item.quantity,
            uint: item.uint,
            unitPrice: item.unitPrice,
            remark: item.remark,
          };
          this.bizQuoteItemList.push(obj);
        });
      });
    },

    sourceTypeChange(key) {
      console.log(key);
    },
    // 選擇銀行詳細信息----------------------------------
    open_dialog_bank() {
      this.dialog_if_bank = true;
    },
    bank_detail(item) {
      this.selected_bank_id = item.id;
      this.form.inBankId = item.id;
      this.form.inBankNo = item.bankNo;
      this.form.inBankAccount = item.accountName;
      this.form.inBankName = item.bankName;

      this.bank_cancel();
    },
    bank_cancel() {
      this.dialog_if_bank = false;
    },
    // ----------------------------------------------------------

    // 選擇 客戶詳細信息----------------------------------
    open_dialog_customer() {
      this.dialog_if_customer = true;
    },
    customer_detail(item) {
      this.selected_customer_id = item.id;

      this.form.customerCode = item.customerCode;
      this.form.customerId = item.id;
      this.form.customerName = item.customerName;
      this.customer_cancel();
    },
    customer_cancel() {
      this.dialog_if_customer = false;
    },
    // ----------選擇預約------------------------------------------------

    open_dialog_reservation() {
      this.dialog_if_reservation = true;
    },
    reservation_detail(item) {
      this.selected_reservation_id = item.id;
      this.form.reservationId = item.id;
      this.form.reservationCode = item.reservationCode;
      this.form.customerId = item.customerId;
      this.form.customerCode = item.customerCode;
      this.form.customerName = item.customerName;
      this.bizQuoteItemList = [];
      item.bizCustomerReservationItemList.map((item) => {
        let obj = {
          itemKey: item.reservationItem,
          itemAmount: "",
          taxAmount: "",
          itemTaxAmount: "",
          taxRate: this.form.taxRate,
          quantity: 1,
          uint: "個",
          unitPrice: "",
          remark: item.remark,
        };
        this.bizQuoteItemList.push(obj);
      });
      this.reservation_cancel();
    },
    reservation_cancel() {
      this.dialog_if_reservation = false;
    },
    //--------------------------------------------------------
    /** 复选框选中數据 */
    SelectionChange(selection) {
      this.checkedList = selection.map((item) => item.index);
    },
    /** 預約事項明細序號 */
    rowItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 預約事項明細添加按钮操作 */
    add() {
      let obj = {};
      obj.itemKey = "";
      obj.itemAmount = "";
      obj.taxAmount = "";
      obj.itemTaxAmount = "";
      obj.taxRate = this.form.taxRate;
      obj.quantity = 1;
      obj.uint = "個";
      obj.unitPrice = "";
      this.bizQuoteItemList.push(obj);
    },
    /** 預約事項明細删除按钮操作 */
    del() {
      if (this.checkedList.length == 0) {
        this.$modal.msgError("請先選擇要删除的明細數据");
      } else {
        const bizQuoteItemList = this.bizQuoteItemList;
        const checkedList = this.checkedList;
        this.bizQuoteItemList = bizQuoteItemList.filter(function (item) {
          return checkedList.indexOf(item.index) == -1;
        });
      }
    },
    // 計算金額
    amountSum(item) {
      this.bizQuoteItemList[item.index - 1].taxRate = this.form.taxRate;
      this.bizQuoteItemList[item.index - 1].taxAmount = this.computeTaxAmount(
        this.bizQuoteItemList[item.index - 1].itemAmount,
        this.form.taxRate
      );
      this.bizQuoteItemList[item.index - 1].itemTaxAmount =
        this.computeItemTaxAmount(
          this.bizQuoteItemList[item.index - 1].itemAmount,
          this.form.taxRate
        );
      this.$forceUpdate();
      this.bizQuoteItemList.splice(1, 0);
    },
    computeTaxAmount(itemAmount, taxRate) {
      return (itemAmount * taxRate).toFixed(2);
    },
    computeItemTaxAmount(itemAmount, taxRate) {
      return (itemAmount * (1 + (taxRate - 0))).toFixed(2);
    },
    // 稅率變化
    taxRate_change() {
      this.bizQuoteItemList.map((item) => {
        item.taxRate = this.form.taxRate;
        item.taxAmount = this.computeTaxAmount(
          item.itemAmount,
          this.form.taxRate
        );
        item.itemTaxAmount = this.computeItemTaxAmount(
          item.itemAmount,
          this.form.taxRate
        );
      });
      this.$forceUpdate();
      this.bizQuoteItemList.splice(1, 0);
    },
    // form.taxRate
    /** 提交按钮 */
    submitForm(type) {
      console.log(this.bizQuoteItemList);
      this.form.taxAmount = 0; //稅金
      this.form.quoteAmount = 0; //報價金額
      this.form.quoteTaxAmount = 0; // 含稅報價
      this.bizQuoteItemList.map((item) => {
        item.unitPrice = item.itemAmount;
        this.form.quoteAmount += item.itemAmount - 0;
        this.form.taxAmount += item.taxAmount - 0;
        this.form.quoteTaxAmount += item.itemTaxAmount - 0;
      });
      // unitPrice
      // (scope.row.itemAmount * form.taxRate).toFixed(2)
      this.form.bizQuoteItemList = this.bizQuoteItemList;
      this.form.quoteSource = this.sourceType;
      this.form.quoteStatus = type;
      console.log(this.form);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateQuote(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.$tab.closePage().then(() => {
              // 执行結束的逻辑
              const obj = { path: "/customer/quote", name: "Quote" };
              this.$tab.refreshPage(obj);
            });
          });
        }
      });
    },
    cancel() {
      this.$tab.closePage().then(() => {
        // 执行結束的逻辑
        const obj = { path: "/customer/quote", name: "Quote" };
        this.$tab.refreshPage(obj);
      });
    },
  },
};
</script>
<style  >
.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
  